<template>
  <div class="post-table-container">
    <!-- 搜索区域 -->
    <a-form
      :model="queryReq"
      :label-col-props="{ span: 6 }"
      :wrapper-col-props="{ span: 18 }"
      label-align="left"
    >
      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item field="title" label="标题">
            <a-input
              v-model="queryReq.title"
              placeholder="请输入帖子标题"
              allow-clear
            >
              <template #prefix>
                <icon-search />
              </template>
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="zone" label="分区">
            <a-select
              v-model="queryReq.zone"
              placeholder="请选择帖子分区"
              allow-clear
              :options="zoneOptions"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="tags" label="标签">
            <a-input-tag
              v-model="queryReq.tags"
              placeholder="请输入帖子标签并回车"
              allow-clear
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" style="text-align: right">
          <a-space>
            <a-button type="primary" @click="pageData">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-form>

    <!-- 表格区域 -->
    <a-table
      :data="data.postList"
      :loading="loading"
      :pagination="pagination"
      @page-change="handlePageNumberChange"
      @page-size-change="handlePageSizeChange"
    >
      <template #columns>
        <a-table-column title="标题" data-index="title" />
        <a-table-column title="分区" data-index="zoneName" align="center" />
        <a-table-column title="标签" data-index="tags">
          <template #cell="{ record }">
            <a-space>
              <a-tag
                v-for="tag in record.tags"
                :key="tag"
                size="small"
                color="arcoblue"
              >
                {{ tag }}
              </a-tag>
            </a-space>
          </template>
        </a-table-column>
        <a-table-column title="点赞数" data-index="thumbNum" align="center" />
        <a-table-column title="收藏数" data-index="favourNum" align="center" />
        <a-table-column title="观看数" data-index="viewNum" align="center" />
        <a-table-column title="操作" align="center">
          <template #cell="{ record }">
            <a-space>
              <a-link @click="handleEdit(record)">编辑</a-link>
              <a-link status="danger" @click="handleDel(record)">删除</a-link>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import {
  Message,
  PaginationProps,
  TableColumnData
} from '@arco-design/web-vue';
import { OjPostQueryRequest, OjPostVo, Paging } from '@/api/gen-api';
import { onMounted, reactive, ref, unref } from 'vue';
import { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
import { OjPostService } from '@/api/gen-api/services/OjPostService.ts';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/store';

// 获取用户信息
const userStore = useUserStore();

// 添加更多调试信息
console.log('组件初始化 - 当前用户信息:', userStore.$state);
console.log('组件初始化 - 当前用户角色:', userStore.role);

const zoneOptions = ref<SelectOptionData[]>([
  {
    label: '综合',
    value: 'synthesis'
  },
  {
    label: '题目讨论',
    value: 'frontend'
  },
  {
    label: '学习分享',
    value: 'backend'
  },
  {
    label: '技术交流',
    value: 'harmony'
  },
  {
    label: '系统反馈',
    value: 'aigc'
  }
]);
const columns: TableColumnData[] = [
  {
    title: '标题',
    dataIndex: 'title',
    align: 'center'
  },
  {
    title: '头像',
    dataIndex: 'avatar',
    align: 'center',
    slotName: 'Avatar'
  },
  {
    title: '分区',
    dataIndex: 'zoneName',
    align: 'center'
  },
  {
    title: '标签',
    dataIndex: 'tags',
    slotName: 'Tags',
    align: 'center'
  },
  {
    title: '点赞数',
    dataIndex: 'thumbNum',
    align: 'center'
  },
  {
    title: '收藏数',
    dataIndex: 'favourNum',
    align: 'center'
  },
  {
    title: '观看数',
    dataIndex: 'viewNum',
    align: 'center'
  },
  {
    slotName: 'Controls',
    title: '操作',
    fixed: 'right',
    align: 'center'
  }
];

const paging: Paging = reactive({
  pageNum: 1,
  pageSize: 5
});

const handlePageSizeChange = (pageSize: number) => {
  paging.pageSize = pageSize;
  pageData();
};

const handlePageNumberChange = (pageNumber: number) => {
  paging.pageNum = pageNumber;
  pageData();
};

const loading = ref(false);
const queryReq = ref<OjPostQueryRequest>({
  title: '',
  zone: '',
  tags: []
});
const data = reactive({
  postList: [] as OjPostVo[]
});
const pagination = reactive<PaginationProps>({
  showTotal: true,
  showPageSize: true,
  pageSizeOptions: [5, 10, 50, 100]
});
/**
 * 查询数据
 */
const pageData = async () => {
  loading.value = true;

  // 方法一：从pinia store获取用户角色信息
  console.log('方法一 - 从pinia store获取用户角色:');
  console.log('  - userStore.$state:', userStore.$state);
  console.log('  - userStore.role:', userStore.role);
  console.log('  - userStore.roles:', userStore.roles);

  // 方法二：直接从localStorage尝试获取用户信息
  console.log('方法二 - 直接从localStorage获取:');
  // 尝试获取用户信息
  let localUserInfo = null;
  try {
    // 尝试从几个常见的key名称获取
    const possibleKeys = ['user', 'userInfo', 'user-info', 'auth'];
    for (const key of possibleKeys) {
      const item = localStorage.getItem(key);
      if (item) {
        try {
          const parsed = JSON.parse(item);
          console.log(`  - 找到localStorage键 ${key}:`, parsed);
          if (parsed.role || parsed.roles) {
            localUserInfo = parsed;
            break;
          }
        } catch (e) {
          console.log(`  - ${key} 解析失败:`, e);
        }
      }
    }

    // 检查pinia持久化存储
    const piniaKey = 'user';
    const piniaStorageKey = `__pinia_${piniaKey}`;
    const piniaData = localStorage.getItem(piniaStorageKey);
    if (piniaData) {
      try {
        const parsed = JSON.parse(piniaData);
        console.log(`  - 找到pinia持久化存储 ${piniaStorageKey}:`, parsed);
        localUserInfo = parsed;
      } catch (e) {
        console.log(`  - pinia存储解析失败:`, e);
      }
    }
  } catch (e) {
    console.error('获取localStorage数据失败:', e);
  }

  // 综合判断用户角色
  let isAdmin = false;
  let adminRoleSource = '';

  // 方法1：检查store中的role字段
  if (typeof userStore.role === 'string') {
    const roleValue = userStore.role.toLowerCase();
    if (roleValue.includes('admin') || roleValue.includes('super')) {
      isAdmin = true;
      adminRoleSource = `store.role值 "${userStore.role}"`;
    }
  }

  // 方法2：检查store中的roles数组
  if (
    !isAdmin &&
    Array.isArray(userStore.roles) &&
    userStore.roles.length > 0
  ) {
    const hasAdminRole = userStore.roles.some(
      role =>
        typeof role === 'string' &&
        (role.toLowerCase().includes('admin') ||
          role.toLowerCase().includes('super'))
    );
    if (hasAdminRole) {
      isAdmin = true;
      adminRoleSource = `store.roles数组 ${JSON.stringify(userStore.roles)}`;
    }
  }

  // 方法3：检查localStorage中的信息
  if (!isAdmin && localUserInfo) {
    // 检查role字段
    if (typeof localUserInfo.role === 'string') {
      const roleValue = localUserInfo.role.toLowerCase();
      if (roleValue.includes('admin') || roleValue.includes('super')) {
        isAdmin = true;
        adminRoleSource = `localStorage.role值 "${localUserInfo.role}"`;
      }
    }

    // 检查roles数组
    if (
      !isAdmin &&
      Array.isArray(localUserInfo.roles) &&
      localUserInfo.roles.length > 0
    ) {
      const hasAdminRole = localUserInfo.roles.some(
        role =>
          typeof role === 'string' &&
          (role.toLowerCase().includes('admin') ||
            role.toLowerCase().includes('super'))
      );
      if (hasAdminRole) {
        isAdmin = true;
        adminRoleSource = `localStorage.roles数组 ${JSON.stringify(localUserInfo.roles)}`;
      }
    }
  }

  // 最终判断结果
  if (isAdmin) {
    console.log(`最终判断: 用户拥有管理员权限，来源: ${adminRoleSource}`);
  } else {
    console.log('最终判断: 用户是普通用户权限');
  }

  try {
    let res;
    if (isAdmin) {
      // 管理员和超级管理员可以看到所有帖子
      console.log('调用管理员API: OjPostService.page');
      res = await OjPostService.page({ page: paging, req: unref(queryReq) });
    } else {
      // 普通用户只能看到自己的帖子
      console.log('调用普通用户API: OjPostService.pageSelf');
      res = await OjPostService.pageSelf({
        page: paging,
        req: unref(queryReq)
      });
    }

    console.log('API返回结果:', res);
    if (res && res.result) {
      const result = res.result;
      data.postList = result.records || [];
      pagination.total = result.totalRow || 0;
      pagination.current = paging.pageNum;
      pagination.pageSize = paging.pageSize;
      console.log('帖子列表数据加载成功，共', data.postList.length, '条记录');
    } else {
      console.error('API返回结果格式异常:', res);
      Message.error('获取帖子列表失败，返回数据格式错误');
      data.postList = [];
    }
  } catch (error) {
    console.error('获取帖子列表失败:', error);
    Message.error('获取帖子列表失败，请稍后重试');
    data.postList = [];
  } finally {
    loading.value = false;
  }
};
const handleDel = (record: OjPostVo) => {
  OjPostService.remove(record.id).then(() => {
    Message.success('删除成功');
    pageData();
  });
};

const router = useRouter();
const handleEdit = (record: OjPostVo) => {
  router.push({ name: 'EditPost', query: { id: record.id } });
};

/**
 * 重置查询条件
 */
const reset = () => {
  queryReq.value = {
    title: '',
    zone: '',
    tags: []
  };
  paging.pageNum = 1;
  pageData();
};

onMounted(() => {
  pageData();
});
</script>

<style scoped lang="less">
.post-table-container {
  background-color: #fff;
  padding: 20px;

  :deep(.arco-form) {
    margin-bottom: 20px;

    .arco-form-item {
      margin-bottom: 16px;
    }

    .arco-input-wrapper,
    .arco-select-view,
    .arco-input-tag {
      width: 100%;
      border-radius: 4px;
    }

    .arco-btn {
      border-radius: 4px;

      &.arco-btn-primary {
        background-color: rgb(86, 82, 255);

        &:hover {
          background-color: rgb(76, 72, 225);
        }
      }

      .arco-icon {
        margin-right: 4px;
      }
    }
  }

  :deep(.arco-table) {
    .arco-table-th {
      background-color: var(--color-fill-1);
      font-weight: 500;
      color: var(--color-text-1);
      border-bottom: 1px solid var(--color-border);
      padding: 12px 16px;
    }

    .arco-table-td {
      padding: 12px 16px;
      border-bottom: 1px solid var(--color-border);
    }

    .arco-table-tr {
      &:hover {
        .arco-table-td {
          background-color: var(--color-fill-1);
        }
      }
    }
  }

  :deep(.arco-tag) {
    border-radius: 4px;
    padding: 0 8px;
    font-size: 12px;
  }

  :deep(.arco-link) {
    font-size: 13px;

    &.arco-link-status-danger {
      margin-left: 12px;
    }
  }
}
</style>
